//
//  TJOauthViewController.m
//  TJSinaWeiBo_OC
//
//  Created by 唐后能 on 16/4/14.
//  Copyright © 2016年 itheima. All rights reserved.
//

#import "TJOauthViewController.h"
#import "MBProgressHUD+PKX.h"
#import "TJAccountViewModle.h"
#import "TJWelcomeViewController.h"
@interface TJOauthViewController ()<UIWebViewDelegate>
@property (nonatomic, weak) UIWebView *wbView;
@end

@implementation TJOauthViewController
//
-(void)loadView {

    UIWebView *webView = [[UIWebView alloc] init];
    self.view = webView;
    self.wbView = webView;
    webView.delegate = self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1,用webView加载授权页.
    [self loadOauthPage];
    
    // 2,创建取消 & 填充 按钮.
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"填充" style:UIBarButtonItemStylePlain target:self action:@selector(fillBtnClicked)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClicked)];
    
    // 3,创建提示框.
    [MBProgressHUD showMessage:@"正在加载..."];
    
}
// 加载授权页.
- (void)loadOauthPage {
    
    UIWebView *webView = (UIWebView *)self.view;
    NSString *urlString = @"https://api.weibo.com/oauth2/authorize?client_id=1523069585&redirect_uri=http://www.baidu.com";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}

//// 获取access_token
//- (void)loadAccess_token:(NSString*)code {
//
//    // 1,准备urlString.
//    NSString *urlString = @"https://api.weibo.com/oauth2/access_token";
//    
//    // 2,授权参数.
//    NSDictionary *parameters = @{
//                            @"client_id": client_id,
//                            @"client_secret": client_secret,
//                            @"grant_type": grant_type,
//                            @"code": code,
//                            @"redirect_uri": redirect_uri
//                            };
//    // 3,发送请求.
//    [[TJNetWorkTool shareNetWorkTool] POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        // 请求成功,保存返回的数据.
//        TJLog(@"%@",responseObject);
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//        // 请求失败.
//        TJLog(@"%@",error);
//    }];
//    
//}

# pragma mark - 加载/填充 按钮点击回调.
// 填充.
- (void)fillBtnClicked {

    // OC执行js代码.

    NSString* js = @"document.getElementById('userId').value = '15814729452';document.getElementById('passwd').value = 'thn&acn243321257'";
    [self.wbView stringByEvaluatingJavaScriptFromString:js];
    
}
// 取消.
- (void)cancelClicked  {

    [self dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark - webView代理方法.
// 是否应该加载请求.
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

//    NSLog(@"%@",request.URL);
    // 先判断是否是授权回调地址.
    BOOL isOauthString = [request.URL.absoluteString hasPrefix:redirect_uri];
    if (!isOauthString) { //如果不是授权回调地址(新浪的请求,要放行)
        return  YES;
    }
    // 是授权回调地址(不是新浪的请求,需拦截)
    // query表示URL的最后一个字串.
    NSString *lastString = request.URL.query;
    NSString *codeString = @"code=";
    // 判断是不是code=开头.
    if ([lastString hasPrefix:codeString]) { //点击了授权
//        TJLog(@"%@",lastString);
        // 截取code.
        NSString *code = [lastString substringFromIndex:codeString.length];
        TJLog(@"%@",code);
        [[TJAccountViewModle shareAccountViewModle] loadAccess_token:code andCallBack:^(NSError *error) {
            if (error!=nil) { //加载token失败.
                TJLog(@"%@",error);
                [MBProgressHUD showError:@"加载token出错!"];
            }
            // 加载token成功,关闭界面,并跳到欢迎界面.
            [self cancelClicked];
            [ MBProgressHUD hideHUD];
            [UIApplication sharedApplication].keyWindow.rootViewController = [[TJWelcomeViewController alloc] init];
        }];

        
    }else { //点击了取消.
        
        // 关闭授权页面.
        [self cancelClicked];
    }
    return NO;
}

// 当webView加载完成后调用.
-(void)webViewDidFinishLoad:(UIWebView *)webView {

    // 隐藏提示框.
    [MBProgressHUD hideHUD];
}

// 当webView加载出错后调用.
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {

//    TJLog(@"%@",error);
    if (error.code == 102) { // 点击了授权或者取消
        return;
    }
    [MBProgressHUD showError:@"网络不给力!"];
}

@end
